import './index.css'
import { useState, createContext, useContext, Component } from 'react'

// 创建一个上下文
const MyContext = createContext()
const { Provider } = MyContext
function Mall() {
  let [name] = useState('Tom')

  return (
    <>
      <div className='parent'>
        <h2>我是父组件,我的名字是{name}</h2>
        <Provider
          value={{
            name
          }}>
          <Child>今天周四</Child>
        </Provider>
      </div>
    </>
  )
}

function Child(props) {
  console.log(props) // 输出：{children: '今天周四'}
  return (
    <>
      <div className='child'>
        <h2>我是子组件,父组件名字为： {props.name}</h2>
        <GrandClass />
        <GrandFun />
      </div>
    </>
  )
}

function GrandFun() {
  const context = useContext(MyContext)
  console.log(context) // 输出：{ name: tom }
  return (
    <>
      <div className='grand'>我是GrandFun组件，祖组件的name：{context.name}</div>
    </>
  )
}

class GrandClass extends Component {
  static contextType = MyContext
  
  componentWillMount() {
    console.log(this.context) // 输出：{ name: tom }
  }

  render() {
    return (
      <>
        <div className='grand'>我是GrandClass组件，祖组件的name：{this.context.name}</div>
      </>
    )
  }
}

export default Mall
